package com.flca.frw.util
{
	import flash.events.EventDispatcher;
	import flash.events.Event;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.events.FaultEvent;
	import mx.core.Application;
	
	public class EventDispatcherUtil 
	{
		private var dispatcher:EventDispatcher;
		private var resultListener:Function;
		private var faultListener:Function;
		
		public function EventDispatcherUtil():void
		{
			// nothing to do.
		}
		
		public function addWebserviceListeners(aDispatcher:EventDispatcher, aResultListener:Function, aFaultListener:Function):void
		{
			dispatcher = aDispatcher;
			resultListener = aResultListener;
			faultListener = aFaultListener;
			
			if (resultListener != null)
			{
				dispatcher.addEventListener("result", handleResultEvent);
			}
			
			if (faultListener != null)
			{
				dispatcher.addEventListener("fault", handleFaultEvent);
			}
			
			dispatcher.addEventListener("fault", Application.application.handleFault);
			
			return;
		}
		
		private function handleResultEvent(aEvent:ResultEvent):void
		{
			removeListeners();
			
			resultListener(aEvent);
			
			dispatcher = null;
			resultListener = null;
			faultListener = null;
		}
		
		private function handleFaultEvent(aEvent:FaultEvent):void
		{
			removeListeners();
			
			faultListener(aEvent);
			
			dispatcher = null;
			resultListener = null;
			faultListener = null;
		}
		
		private function removeListeners():void
		{
			dispatcher.removeEventListener("result", handleResultEvent);
			dispatcher.removeEventListener("fault", handleFaultEvent);
			dispatcher.removeEventListener("fault", Application.application.handleFault);
		}
	}
}